package controller

import (
	"bytes"
	"dub/define/grpcmodel"
	"dub/secrec"
	"dub/utils"
	"fmt"
	"github.com/astaxie/beego"
	"strconv"
	"strings"
	"time"
)

type IndexController struct {
	beego.Controller
}

//首页
func (i *IndexController) Get() {
	i.TplName = "index.html"
}

//分享的页面
func (i *IndexController) Share() {
	userid, _ := i.GetUint32(":userid", 0)
	postid, _ := i.GetUint32(":postid", 0)
	for {
		use_rpc := secrec.GetRpc(secrec.ConstServiceUseRpc)
		if use_rpc == nil {

			utils.NewLogger().Errorf("indexController.go Share method not find use_rpc info GetRpc\n")
			i.Abort("404")
			break
		}
		sec_advert := grpcmodel.NewISecRpcAdvertClient(use_rpc.Conn())
		args := &grpcmodel.ModelSecRpcAdvertReqFind{
			AdvertId: uint32(postid),
		}

		reply, err := sec_advert.FindAdvert(use_rpc.Context(), args)
		if err != nil {
			utils.NewLogger().Errorf("indexController.go add Share sec_advert.FindAdvert err. %v\n", err)
			i.Abort("404")
			break
		}
		if reply.GetErr() > 0 {
			i.Abort("404")
			break
		}

		i.TplName = "share.html"
		break
	}
	go addValPostCount(userid, postid, i.Ctx.Request.RemoteAddr)
}

var (
	//postid and format ip-timestamp more split use '_'
	postValidCount = make(map[uint32]string)
)

func addValPostCount(userid, postid uint32, ip string) {
	for {
		if ip == "" {
			break
		}
		now_unix := time.Now().Unix()
		str_ips, ips_ok := postValidCount[postid]
		//如果不存在则直接添加
		if !ips_ok {
			postValidCount[postid] = fmt.Sprintf("%s-%d", ip, now_unix)
			addPostCount(userid, postid)
			break
		}

		ip_infos := strings.Split(str_ips, "_")
		ip_info := ""
		info_index := 0
		//查找是否有重复的ip
		for i, info := range ip_infos {
			if strings.HasPrefix(info, ip) {
				ip_info = info
				info_index = i
				break
			}
		}

		//如果ip不存在则有效
		if ip_info == "" {
			postValidCount[postid] = fmt.Sprintf("%s_%s-%d", str_ips, ip, now_unix)
			addPostCount(userid, postid)
			break
		}

		old_unix, _ := strconv.Atoi(ip_info[strings.Index(ip_info, "-")+1:])
		//如果在两个小时以内则表示无效
		if now_unix-int64(old_unix) < 7200 {
			break
		}

		ip_infos[info_index] = fmt.Sprintf("%s-%d", ip, now_unix)
		buf := bytes.Buffer{}
		for i, info := range ip_infos {
			buf.WriteString(info)
			if i > 0 {
				buf.WriteString("_")
			}
		}
		postValidCount[postid] = buf.String()
		addPostCount(userid, postid)
		break
	}
}

func addPostCount(userid, postid uint32) {
	use_rpc := secrec.GetRpc(secrec.ConstServiceUseRpc)
	if use_rpc == nil {
		utils.NewLogger().Errorf("indexController.go Share method not find use_rpc info GetRpc\n")
		return
	}
	sec_advert := grpcmodel.NewISecRpcAdvertClient(use_rpc.Conn())
	args := &grpcmodel.ModelSecRpcAdvertReqModel{
		IsAllUpdate: false,
		ModelSecRpcAdvert: &grpcmodel.ModelSecRpcAdvert{
			AdvertId: postid,
			AdCount:  uint32(1),
		},
	}
	sec_advert.Update(use_rpc.Context(), args)

	//TODO:添加往表dubageadv里添加数据
}
